if(!window.xflib || !window.xflib.client) window.xflib = { client: {} }

xflib.client.CategoryUi = class CategoryUi {

    constructor(categoryService){
        this.categoryService = categoryService;
        this.categories = new Map();
        this.categoryModal = new xflib.client.CategoryModal();
        this.categorySelect = document.getElementById('category-select');

        document.getElementById('categoryAddbtn').addEventListener('click', this.addCategoryHandler.bind(this));
        document.getElementById('categoryEditbtn').addEventListener('click', this.editCategoryHandler.bind(this));
        document.getElementById('categoryDeleteBtn').addEventListener('click', this.deleteCategoryHandler.bind(this));    
    }

    async addCategoryHandler(){
        this.categoryModal.openModal('add', (categoryCode, categoryName, tag) => this.saveCategory(categoryCode, categoryName, tag));
    }

    async editCategoryHandler(){
        const categoryCode = this.categorySelect.options[this.categorySelect.selectedIndex].value;
        const categoryName = this.categorySelect.options[this.categorySelect.selectedIndex].data;

        if(categoryCode === 'all'){
            alert('请选择需要编辑的分类');
            return;
        }

        this.categoryModal.openModal('edit', (categoryCode, categoryName, tag) => this.saveCategory(categoryCode, categoryName, tag), categoryCode, categoryName); 
    }

    async deleteCategoryHandler(){
        this.deleteCategory();
    }

    async saveCategory(categoryCode, categoryName, tag){
        const _this = this;
        return new Promise((resolve, reject) => {
            if ([..._this.categories.keys()].includes(categoryCode) && _this.categories.get(categoryCode) === categoryName) {
                alert('分类名称不能重复');
                reject(false);
            }

            try {
                _this.categories.set(categoryCode, categoryName);
                if(tag === 'add'){
                    _this.categoryService.create(categoryCode, categoryName).then(response => {
                        if(response.success){
                            _this.refreshCategorySelect(categoryCode);
                        }
                    });
                } else if(tag === 'edit'){
                    const oldValue = this.categorySelect.options[this.categorySelect.selectedIndex].value;
                    _this.categoryService.update(oldValue, categoryCode, categoryName).then(response => {
                        if(response.success){
                            _this.refreshCategorySelect(categoryCode);
                        }
                    });
                }

                resolve(true);
            } catch(e) {
                reject(false);
            }
        });
    }

    async deleteCategory() {
        const selectedCategory = this.categorySelect.value;
        if (selectedCategory === 'all') {
            alert('请选择要删除的分类');
            return;
        }

        const projectService = window.xflib.client.Application.getBean('projectService');
        const projects = await projectService.queryByCategory(selectedCategory);
        if (projects &&Object.entries(projects).length > 0) {
            alert(`分类 "${this.categorySelect.options[this.categorySelect.selectedIndex].data}" 已被使用，不能删除!`);
            return;
        }

        if (!confirm(`确定要删除分类 "${this.categorySelect.options[this.categorySelect.selectedIndex].data}" 吗？`)) {
            return;
        }

        const _this = this;
        _this.categories.delete(selectedCategory);
        _this.categoryService.delete(selectedCategory).then(response => {
            if(response.success){
                _this.refreshCategorySelect();
            }
        });
    }

    async refreshCategorySelect(value = 'all') {
        this.categoryService.queryByCategoryCodes().then(response => {
            if(response){
                this.categories = new Map(Object.entries(response));
                this.categorySelect.innerHTML = '<option value="all">全部</option>';
                this.categories.forEach((name, code) => {
                    const option = document.createElement('option');
                    option.value = code;
                    option.data = name;
                    option.textContent = code + ' - ' + name;
                    this.categorySelect.appendChild(option);
                    this.categorySelect.value = value;
                });
                xflib.client.ProjectModal.projectCategorySelect().innerHTML = this.categorySelect.innerHTML;
            }
        });
        this.categorySelect.value = value;
    }
} 